<template>
  <view class="benefit-goods">
    <!-- 商品规格选择 -->
    <view class="product-duration-section" v-if="goodsInfo.specs && goodsInfo.specs.length > 0">
      <text class="section-title">商品规格</text>
      <view class="option-buttons">
        <view 
          class="option-btn" 
          :class="{ active: selectedSpec && selectedSpec.id === spec.id }" 
          @click="selectSpec(spec)"
          v-for="spec in goodsInfo.specs" 
          :key="spec.id"
        >
          <text class="option-text">{{ spec.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 充值账号类型选择 -->
    <view class="product-duration-section">
      <text class="section-title">充值账号类型</text>
      <view class="option-buttons">
        <view 
          class="option-btn" 
          :class="{ active: selectedAccountType && selectedAccountType.id === accountType.id }" 
          @click="selectAccountType(accountType)"
          v-for="accountType in accountTypes" 
          :key="accountType.id"
        >
          <text class="option-text">{{ accountType.name }}</text>
        </view>
      </view>
    </view>
    
    <!-- 充值账号填写 -->
    <view class="account-section">
      <!-- 充值账号三列布局容器 -->
      <view class="account-header-container">
        <text class="section-title">充值账号</text>
        <view class="account-type-btn" :class="{ active: accountInputType === 'single' }" @click="selectAccountInputType('single')">
          <view class="radio-icon" :class="{ active: accountInputType === 'single' }"></view>
          <text class="account-type-text">单个账号</text>
        </view>
        <view class="account-type-btn" :class="{ active: accountInputType === 'multiple' }" @click="selectAccountInputType('multiple')">
          <view class="radio-icon" :class="{ active: accountInputType === 'multiple' }"></view>
          <text class="account-type-text">多个账号</text>
        </view>
      </view>
      
      <!-- 输入框容器 -->
      <view class="account-input-container">
        <view class="input-wrapper">
          <!-- 单个账号输入框 -->
          <input 
            v-if="accountInputType === 'single'"
            class="account-input" 
            type="text" 
            :placeholder="getAccountPlaceholder()" 
            v-model="accountNumber" 
          />
          
          <!-- 多个账号多行输入框 -->
          <textarea 
            v-if="accountInputType === 'multiple'"
            ref="multipleAccountsTextarea"
            class="account-textarea"
            :placeholder="getAccountPlaceholder()"
            v-model="multipleAccountsText"
            @input="onMultipleAccountsInput"
            @focus="onTextareaFocus"
            @blur="onTextareaBlur"
            auto-height
            :maxlength="10000"
            :adjust-position="true"
            :cursor-spacing="20"
          ></textarea>
        </view>
      </view>
    </view>
    
    <!-- 购买数量 -->
    <view class="quantity-section">
      <text class="section-title">购买数量</text>
      <view class="quantity-control">
        <view class="quantity-btn" @click="decreaseQuantity">
          <text class="quantity-btn-text">-</text>
        </view>
        <text class="quantity-btn-text">|</text>
        <text class="quantity-value">{{ quantity }}</text>
        <text class="quantity-btn-text">|</text>
        <view class="quantity-btn" @click="increaseQuantity">
          <text class="quantity-btn-text">+</text>
        </view>
      </view>
    </view>
    
    <!-- 成交记录 -->
    <view class="transaction-section">
      <text class="section-title">成交记录</text>
      <view class="transaction-table">
        <!-- 表头 -->
        <view class="table-header">
          <text class="header-cell time-cell">成交时间</text>
          <text class="header-cell price-cell">价格</text>
          <text class="header-cell duration-cell">耗时</text>
        </view>
        <!-- 表格内容 -->
        <view class="table-body">
          <view class="table-row" v-for="(record, index) in transactionRecords" :key="index" :class="{ 'even-row': index % 2 === 1 }">
            <text class="body-cell time-cell">{{ record.time }}</text>
            <text class="body-cell price-cell">{{ record.price }}</text>
            <text class="body-cell duration-cell">{{ record.duration }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 销售渠道 -->
    <view class="channel-section">
      <text class="section-title">充值渠道</text>
      
      <!-- 支持的平台 -->
      <view class="platform-grid">
        <view 
          class="platform-item" 
          :class="{ supported: goodsInfo.channel_ids && goodsInfo.channel_ids.includes(platform.id), unsupported: !goodsInfo.channel_ids || !goodsInfo.channel_ids.includes(platform.id) }"
          v-for="platform in platformList" 
          :key="platform.id"
        >
          <image 
            class="platform-icon" 
            :src="goodsInfo.channel_ids && goodsInfo.channel_ids.includes(platform.id) ? '/static/Images/goods/Zhichi.png' : '/static/Images/goods/Buzhichi.png'" 
            mode="aspectFit"
          ></image>
          <text class="platform-text">{{ platform.name }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { validatePhone, validateEmail } from '@/utils/validate.js'

export default {
  name: 'BenefitGoods',
  props: {
    goodsInfo: {
      type: Object,
      required: true
    },
    initialSelectedSpec: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      selectedSpec: null,
      accountTypes: [],
      selectedAccountType: null,
      accountInputType: 'single',
      accountNumber: '',
      accountList: [],
      multipleAccountsText: '',
      quantity: 1,
      platformList: [
        { id: 1, name: '咸鱼' },
        { id: 2, name: '得物' },
        { id: 3, name: '小红书' },
        { id: 4, name: '拼多多' },
        { id: 5, name: '淘宝' },
        { id: 6, name: '京东' },
        { id: 7, name: '抖音' },
        { id: 8, name: '限购' },
        { id: 9, name: 'API充值' }
      ],
      transactionRecords: [
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' },
        { time: '2025-05-29', price: '¥950', duration: '1小时30分' }
      ]
    }
  },
  watch: {
    initialSelectedSpec: {
      handler(newVal) {
        if (newVal) {
          this.selectedSpec = newVal;
        }
      },
      immediate: true
    },
    // 监听输入框内容变化，实时更新账号数量
    accountNumber: {
      handler() {
        this.emitAccountData();
      }
    }
  },
  mounted() {
    // 如果有规格，默认选择第一个规格
    if (this.goodsInfo.specs && this.goodsInfo.specs.length > 0 && !this.selectedSpec) {
      this.selectedSpec = this.goodsInfo.specs[0];
      this.$emit('spec-change', this.selectedSpec);
    }
    
    // 获取账号类型数据
    this.fetchAccountTypes();
    
    // 初始化时向父组件传递数量
    this.emitQuantityChange();
  },
  methods: {
    // 选择商品规格
    selectSpec(spec) {
      this.selectedSpec = spec;
      this.$emit('spec-change', spec);
    },
    
    // 选择充值账号类型
    selectAccountType(accountType) {
      this.selectedAccountType = accountType;
      this.$emit('account-type-change', accountType);
    },
    
    // 选择账号输入类型（单个/多个）
    selectAccountInputType(type) {
      this.accountInputType = type;
      
      // 切换到单账号模式时，如果有多个账号，取第一个作为默认值
      if (type === 'single' && this.accountList.length > 0) {
        this.accountNumber = this.accountList[0];
        this.accountList = [];
        this.multipleAccountsText = '';
      }
      
      // 切换到多账号模式时，如果有单个账号，添加到多行文本中
      if (type === 'multiple' && this.accountNumber.trim()) {
        this.multipleAccountsText = this.accountNumber.trim();
        this.accountList = [this.accountNumber.trim()];
        this.accountNumber = '';
      }
      
      this.emitAccountData();
    },
    
    // 获取账号输入框占位符
    getAccountPlaceholder() {
      if (this.accountInputType === 'multiple') {
        if (this.selectedAccountType) {
          if (this.selectedAccountType.name === '手机号') {
            return '请输入手机号，每行一个账号';
          } else if (this.selectedAccountType.name === '邮箱') {
            return '请输入邮箱地址，每行一个账号';
          }
        }
        return '请输入账号，每行一个账号';
      } else {
        if (this.selectedAccountType) {
          if (this.selectedAccountType.name === '手机号') {
            return '请输入您需要充值的手机号';
          } else if (this.selectedAccountType.name === '邮箱') {
            return '请输入您需要充值的邮箱地址';
          }
        }
        return '请输入您需要充值的账号';
      }
    },
    
    // 监听多行账号输入变化
    onMultipleAccountsInput() {
      // 将多行文本转换为账号列表
      const lines = this.multipleAccountsText.split('\n').filter(line => line.trim());
      this.accountList = lines.map(line => line.trim());
      
      // 实时发送数据给父组件
      this.emitAccountData();
      
      // 自动滚动到输入框位置
      this.scrollToTextarea();
    },
    
    // 输入框获得焦点时的处理
    onTextareaFocus() {
      this.$nextTick(() => {
        this.scrollToTextarea();
      });
    },
    
    // 输入框失去焦点时的处理
    onTextareaBlur() {
      // 可以在这里添加失去焦点时的处理逻辑
    },
    
    // 滚动到输入框位置
    scrollToTextarea() {
      this.$nextTick(() => {
        try {
          // 获取输入框元素
          const textarea = this.$refs.multipleAccountsTextarea;
          if (textarea) {
            // 使用uni.createSelectorQuery()获取元素位置信息
            const query = uni.createSelectorQuery().in(this);
            query.select('.account-textarea').boundingClientRect((rect) => {
              if (rect) {
                // 计算需要滚动的位置
                const scrollTop = rect.top - 100; // 留出100rpx的缓冲区域
                
                // 执行页面滚动
                uni.pageScrollTo({
                  scrollTop: Math.max(0, scrollTop),
                  duration: 300
                });
              }
            }).exec();
          }
        } catch (error) {
          console.log('滚动处理出错:', error);
        }
      });
    },
    
    // 添加账号
    addAccount() {
      if (!this.accountNumber || !this.accountNumber.trim()) {
        uni.showToast({
          title: '请输入账号',
          icon: 'none'
        });
        return;
      }
      
      const account = this.accountNumber.trim();
      
      // 根据账号类型验证格式
      if (this.selectedAccountType) {
        if (this.selectedAccountType.name === '手机号' && !validatePhone(account)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          });
          return;
        }
        if (this.selectedAccountType.name === '邮箱' && !validateEmail(account)) {
          uni.showToast({
            title: '请输入正确的邮箱地址',
            icon: 'none'
          });
          return;
        }
      }
      
      // 检查是否已存在
      if (this.accountList.includes(account)) {
        uni.showToast({
          title: '账号已存在',
          icon: 'none'
        });
        return;
      }
      
      // 添加到列表
      this.accountList.push(account);
      this.accountNumber = ''; // 清空输入框
      
      uni.showToast({
        title: '账号添加成功',
        icon: 'success'
      });
      
      this.emitAccountData();
    },
    
    // 移除账号
    removeAccount(index) {
      this.accountList.splice(index, 1);
      uni.showToast({
        title: '账号已移除',
        icon: 'success'
      });
      this.emitAccountData();
    },
    
    // 发送账号数据给父组件
    emitAccountData() {
      // 计算账号数量
      let accountCount = 0;
      if (this.accountInputType === 'multiple') {
        // 多账号模式：统计账号列表的数量
        accountCount = this.accountList.length;
      } else {
        // 单账号模式：只看输入框是否有内容
        accountCount = this.accountNumber && this.accountNumber.trim() ? 1 : 0;
      }
      
      console.log('BenefitGoods组件发送账号数据:');
      console.log('- accountType:', this.accountInputType);
      console.log('- accountList:', this.accountList);
      console.log('- accountNumber:', this.accountNumber);
      console.log('- multipleAccountsText:', this.multipleAccountsText);
      console.log('- 计算的accountCount:', accountCount);
      
      this.$emit('account-change', {
        accountType: this.accountInputType,
        accountNumber: this.accountNumber,
        accountList: this.accountList,
        multipleAccountsText: this.multipleAccountsText,
        selectedAccountType: this.selectedAccountType,
        accountCount: accountCount
      });
    },
    
    // 获取账号类型列表
    async fetchAccountTypes() {
      try {
        const { goodsApi } = await import('@/utils/api');
        const response = await goodsApi.getGoodsTemps();
        if (response.code === 1 && response.data && response.data.length > 0) {
          // 获取第一个账号类型模板的temp_list
          this.accountTypes = response.data[0].temp_list || [];
        }
      } catch (error) {
        console.error('获取账号类型失败:', error);
      }
    },
    
    // 验证账号数据
    validateAccountData() {
      if (this.accountInputType === 'single') {
        if (!this.accountNumber || !this.accountNumber.trim()) {
          return { valid: false, message: '充值账号不能为空' };
        }
        
        const singleAccount = this.accountNumber.trim();
        
        // 根据账号类型验证格式
        if (this.selectedAccountType) {
          if (this.selectedAccountType.name === '手机号' && !validatePhone(singleAccount)) {
            return { valid: false, message: '充值账号不是手机号' };
          }
          if (this.selectedAccountType.name === '邮箱' && !validateEmail(singleAccount)) {
            return { valid: false, message: '充值账号不是邮箱地址' };
          }
        }
        
        return { valid: true, accounts: singleAccount };
      } else {
        // 多账号模式 - 收集所有账号（已添加的 + 输入框中的）
        let allAccounts = [...this.accountList];
        
        // 如果输入框中还有账号，也加入到列表中
        if (this.accountNumber && this.accountNumber.trim()) {
          const inputAccount = this.accountNumber.trim();
          if (!allAccounts.includes(inputAccount)) {
            allAccounts.push(inputAccount);
          }
        }
        
        if (allAccounts.length === 0) {
          return { valid: false, message: '请至少添加一个充值账号' };
        }
        
        // 根据账号类型验证所有账号格式
        if (this.selectedAccountType) {
          for (let account of allAccounts) {
            if (this.selectedAccountType.name === '手机号' && !validatePhone(account)) {
              return { valid: false, message: '充值账号不是手机号' };
            }
            if (this.selectedAccountType.name === '邮箱' && !validateEmail(account)) {
              return { valid: false, message: '充值账号不是邮箱地址' };
            }
          }
        }
        
        return { valid: true, accounts: allAccounts };
      }
    },
    
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
        this.emitQuantityChange();
      }
    },
    
    // 增加数量
    increaseQuantity() {
      const maxStock = this.getCurrentStock();
      if (this.quantity < maxStock) {
        this.quantity++;
        this.emitQuantityChange();
      } else {
        uni.showToast({
          title: `您购买数量已超库存上限`,
          icon: 'none'
        });
      }
    },
    
    // 向父组件传递数量变化
    emitQuantityChange() {
      this.$emit('quantity-change', this.quantity);
    },
    
    // 获取当前库存
    getCurrentStock() {
      if (this.selectedSpec && this.selectedSpec.stock) {
        return this.selectedSpec.stock;
      }
      return this.goodsInfo.stock || 999;
    }
  }
}
</script>

<style scoped>

/* 商品规格选择 */
.product-duration-section {
  background-color: #ffffff;
  padding: 16px;
  margin: 1rem;
  border-radius: 12px;

}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 12px;
}

.option-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 0.8rem;
}

.option-btn {
  padding: 0.4rem 0.8rem;
  border: 2px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  transition: all 0.3s ease;
}

.option-btn.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.option-text {
  font-size: 14px;
  color: #666666;
}

.option-btn.active .option-text {
  color: #ff4757;
  font-weight: 500;
}

/* 充值账号填写 */
.account-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 充值账号三列布局容器 */
.account-header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 0 8px;
}

.account-header-container .section-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  margin: 0;
}

.account-type-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
  flex: 0 0 auto;
}

.account-type-btn:hover {
  background-color: #f8f9fa;
}

.account-type-btn.active {
  background-color: #f0f8ff;
}

.radio-icon {
  width: 12px;
  height: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  background-color: #ffffff;
  position: relative;
  transition: all 0.3s ease;
}

.radio-icon.active {
  border-color: #ff4757;
  background-color: #ff4757;
}

.radio-icon.active::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
}

.account-type-text {
  font-size: 14px;
  color: #333333;
}

/* 输入框和添加按钮两列布局容器 */
.account-input-container {
  margin-top: 16px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.account-input {
  width: 100%;
  height: 36px;
  padding: 0 56px 0 16px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  background-color: #f8f9fa;
  font-size: 14px;
  color: #333333;
  outline: none;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.account-input:focus {
  border-color: #ff4757;
  background-color: #ffffff;
}

.account-input::placeholder {
  color: #999999;
}

.account-textarea {
  width: 100%;
  min-height: 36px;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  font-size: 14px;
  background-color: #f8f9fa;
  color: #333333;
  outline: none;
  transition: all 0.3s ease;
  box-sizing: border-box;
  resize: none;
  line-height: 1.4;
}

.account-textarea:focus {
  border-color: #ff4757;
  background-color: #ffffff;
}

.account-textarea::placeholder {
  color: #999999;
}

.floating-icon {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
  width: 20px;
  height: 20px;
}

.floating-icon:hover {
  transform: translateY(-50%) scale(1.1);
}

/* 多账号列表 */
.account-list {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.account-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 16px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 20px;
  transition: all 0.3s ease;
  height: 24px;
}

.account-item:last-child {
  margin-bottom: 0;
}

.account-item:hover {
  background-color: #e9ecef;
}

.account-text {
  flex: 1;
  font-size: 14px;
  color: #333333;
  word-break: break-all;
}

.remove-account-btn {
  width: 24px;
  height: 24px;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 8px;
  transition: all 0.3s ease;
}

.remove-account-btn:hover {
  background-color: #ff3742;
  transform: scale(1.1);
}

.remove-icon-img {
  width: 24px;
  height: 24px;
}

/* 购买数量 */
.quantity-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  background-color: #ffffff;
  overflow: hidden;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.quantity-btn:hover {
  background-color: #f8f9fa;
}

.quantity-btn-text {
  font-size: 18px;
  color: #666666;
  font-weight: 500;
}

.quantity-value {
  font-size: 16px;
  color: #333333;
  margin: 0 16px;
  min-width: 24px;
  text-align: center;
  font-weight: 500;
}

/* 成交记录 */
.transaction-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.transaction-table {
  margin-top: 16px;
  border-radius: 8px;
}

.table-header {
  display: flex;
  background-color: #f5f5f5;
  padding: 12px 0;
  border-radius: 0.4rem;
}

.table-body {
  background-color: #ffffff;
}

.table-row {
  display: flex;
  padding: 0.25rem 0;
}

.table-row:last-child {
  border-bottom: none;
}

.table-row.even-row {
  background-color: #f9f9f9;
  border-radius: 0.5rem;
}

.header-cell,
.body-cell {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.header-cell {
  color: #666666;
  font-weight: 500;
}

.body-cell {
  color: #333333;
}

.time-cell {
  flex: 1.2;
}

.price-cell {
  flex: 0.8;
}

.duration-cell {
  flex: 1;
}

/* 销售渠道 */
.channel-section {
  padding: 20px 16px;
  background-color: #ffffff;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.platform-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
  margin-bottom: 24px;
  justify-content: flex-start;
}

.platform-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.platform-icon {
  width: 1rem;
  height: 1rem;
  flex-shrink: 0;
}

.platform-text {
  font-size: 0.75rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.platform-item.supported .platform-text {
  color: #111111;
}

.platform-item.unsupported .platform-text {
  color: #999999;
}
</style>